package cn.qu.dockman.mgr.disparte;

import cn.qu.dockman.mgr.entity.Host;
import cn.qu.dockman.mgr.entity.Image;
import cn.qu.dockman.mgr.service.HostService;
import cn.qu.dockman.mgr.service.ImageService;
import cn.qu.dockman.protocol.command.client.ImageListCommand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by zh on 17/3/16.
 */
public class ImageListObserver implements Observer {

    public ImageListObserver(DispartMgr dispartMgr) {
        dispartMgr.addObserver(this);
    }

    @Autowired
    private HostService hostService;

    @Autowired
    private ImageService imageService;

    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof ArgDef) {
            ArgDef def = (ArgDef) arg;
            switch (def.getName()) {
                case ImageListCommand.NAME: {
                    ImageListCommand.ImageListBody body = (ImageListCommand.ImageListBody) def.getData();

                    Host host = hostService.findByIp(def.getHost());
                    if (host != null) {
                        Image image = imageService.findByHostIdAndImageId(host.getId(), body.getId());
                        if (image == null) {
                            image = new Image();
                        }

                        image.setCreateTime(new Date(body.getCreated() * 1000));
                        image.setHostId(host.getId());
                        image.setImageId(body.getId());
                        image.setImageLatest(StringUtils.join(body.getRepoTags(), ","));
                        image.setImageSize(body.getSize().intValue());
                        image.setImageText(body.getId());
                        image.setImageName(body.getId());
                        image.setImageUrl(body.getId());
                        imageService.saveOrUpdate(image);
                    }
                }
                break;
            }
        }
    }
}
